package com.emou.spring;

import com.emou.model.Admin;
import com.emou.service.AdminService;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Emou on 2021/1/15
 */
public class ClassPathXmlApplicationContext implements BeanFactory {
    private Map<String, Object> beans = new HashMap<>();

    public ClassPathXmlApplicationContext() throws JDOMException, IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml"));
        Element root = document.getRootElement();
        List<Element> list = root.getChildren();
        for (int i = 0; i < list.size(); i++) {
            Element element = list.get(i);
            String id = element.getAttributeValue("id");
            String clazz = element.getAttributeValue("class");
            Object o = Class.forName(clazz).newInstance();
            beans.put(id, o);
            for (Element propertyElement : (List<Element>) element.getChildren()) {
                String name = propertyElement.getAttributeValue("name");
                String bean = propertyElement.getAttributeValue("bean");
                Object beanObject = beans.get(bean);
                String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
                Method method = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
                method.invoke(o, beanObject);
            }
        }
    }

    public static void main(String[] args) throws JDOMException, IOException, IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext();
        AdminService service = (AdminService) beanFactory.getBean("adminService");
        service.save(new Admin());
    }
    @Override
    public Object getBean(String id) {
        return beans.get(id);
    }
}
